﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace BridgeShips
{
    /// <summary>
    /// 管理器管理类
    /// </summary>
    public class Managers
    {
        private LinkedList<IControl> m_Managers;

        public Managers()
        {
            m_Managers = new LinkedList<IControl>();
        }

        public IControl GetManager<T>()
        {
            LinkedListNode<IControl> currentNode = m_Managers.First;
            Type type = typeof(T);
            while (currentNode != null)
            {
                if (type == currentNode.Value.GetType())
                    return currentNode.Value;
                currentNode = currentNode.Next;
            }
            return null;
        }

        public IControl AddManager<T>()
            where T : IControl, new()
        {
            IControl manager = GetManager<T>();
            
            if (manager == null)
            {
                manager = new T();
                m_Managers.AddLast(manager);
            }
            return manager;
        }

        public void Init(EntityBase entity)
        {
            LinkedListNode<IControl> currentNode = m_Managers.First;
            while (currentNode != null)
            {
                currentNode.Value.Init(entity);
                currentNode = currentNode.Next;
            }
        }

        public void InitDown()
        {
            LinkedListNode<IControl> currentNode = m_Managers.First;
            while (currentNode != null)
            {
                currentNode.Value.InitDown();
                currentNode = currentNode.Next;
            }
        }

        public void PostInit() {
            LinkedListNode<IControl> currentNode = m_Managers.First;
            while (currentNode != null) {
                currentNode.Value.PostInit();
                currentNode = currentNode.Next;
            }
        }
        public void Update(float frameTime, float realTime)
        {
            LinkedListNode<IControl> currentNode = m_Managers.First;

            while (currentNode != null) {
                currentNode.Value.Update(frameTime, realTime);
                currentNode = currentNode.Next;
                
            }
            
        }
        public void Release()
        {
            LinkedListNode<IControl> currentNode = m_Managers.First;
            while (currentNode != null)
            {
                currentNode.Value.Release();
                currentNode = currentNode.Next;
            }
            m_Managers.Clear();
            m_Managers = null;
        }
    }
}
